/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import java.util.ArrayList;
import java.util.Random;
import local.QuestionFacadeLocal;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.Configuration;
import model.Question;
import model.Theme;

/**
 *
 * @author Randy
 */
@Stateless
public class QuestionFacade implements QuestionFacadeLocal {

    @PersistenceContext(unitName = "IEMPPU")
    private EntityManager em;

    @Override
    public ArrayList<Question> getQuestions(Long theme_id) {
        ArrayList<Question> qList = new ArrayList<Question>();
        Theme t = em.find(Theme.class, theme_id);

        for (Question q : t.getQuestion()) {
            qList.add(q);
        }

        return qList;
    }

    @Override
    public void updateQuestion(Long qns_id, String question, String status) {
        Question q = em.find(Question.class, qns_id);

        q.setQuestion(question);
        q.setStatus(Question.QuestionStatus.valueOf(status));
        em.merge(q);
    }

    @Override
    public void createQuestion(Long theme, String question) {
        Question q = new Question();
        q.setQuestion(question);
        q.setStatus(Question.QuestionStatus.Active);

        em.persist(q);

        Theme t = em.find(Theme.class, theme);
        t.getQuestion().add(q);
        em.merge(t);
    }

    @Override
    public ArrayList<Question> findQnsByThemes(Theme[] themes, Configuration config) {
        ArrayList<Question> qlist = new ArrayList<Question>();
        for (int i = 0; i < themes.length; i++) {
            for (Question qn : ((Theme) themes[i]).getQuestion()) {
                qn.setTheme_id(((Theme) themes[i]).getTheme_id());
                qlist.add(qn);

            }
        }
        ArrayList<Question> newlist = new ArrayList<Question>();

        if (config.getStatus() == Configuration.ConfigurationStatus.True) {
            while (true) {
                if (qlist.isEmpty()) {
                    break;
                }
                Random randomGenerator = new Random();
                int index = randomGenerator.nextInt(qlist.size());
                if (qlist.get(index).getStatus() == Question.QuestionStatus.Active) {
                    newlist.add(qlist.get(index));
                }
                qlist.remove(index);
            }
        } else {
            for (Question e : qlist) {
                if (e.getStatus() == Question.QuestionStatus.Active) {
                    newlist.add(e);
                }
            }
        }
        return newlist;
    }

    @Override
    public void edit(Question a) {
        em.merge(a);
    }
}
